package com.heng.futureDemo;

import org.junit.Test;

import java.util.concurrent.*;

public class ACompletableFutureUseDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ExecutorService threadPool = Executors.newFixedThreadPool(3);
        try {
            CompletableFuture.supplyAsync(() -> {
                System.out.println(Thread.currentThread().getName() + "---come in");
                int result = ThreadLocalRandom.current().nextInt(10);
                try {TimeUnit.SECONDS.sleep(1);}catch (InterruptedException e){e.printStackTrace();}
                System.out.println("---1秒钟后出结果： "  + result);
                return result;
            },threadPool).whenComplete((v,e)->{
                if(e == null) {
                    System.out.println("---计算结果完成: " + v);
                }
            }).exceptionally(e -> {
                e.printStackTrace();
                System.out.println("异常情况" + e.getCause() + "\t" + e.getMessage());
                return null;
            });
            //也就是说，线程不会堵塞！！！
            System.out.println(Thread.currentThread().getName() + "线程先去忙其他任务");
        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            threadPool.shutdown();
        }

        try {TimeUnit.SECONDS.sleep(3);}catch (InterruptedException e){e.printStackTrace();}
    }



    @Test
    public   void m1() throws InterruptedException, ExecutionException {
        CompletableFuture<Integer> completableFuture = CompletableFuture.supplyAsync(() -> {
            System.out.println(Thread.currentThread().getName() + "---come in");
            int result = ThreadLocalRandom.current().nextInt(10);
            try {TimeUnit.SECONDS.sleep(1);}catch (InterruptedException e){e.printStackTrace();}

            System.out.println("---1秒钟后出结果： "  + result);
            return result;
        });
        System.out.println(Thread.currentThread().getName() + "线程先去忙其他任务");
        System.out.println(completableFuture.get());
    }
}
